// 云函数入口文件
const cloud = require("wx-server-sdk");
// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  traceUser: true,
  env: 'micro-i98sq'
});
const db = cloud.database();
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  var dbName = event.dbName ? event.dbName : 'movies';
  var filter = event.filter ? event.filter : "";
  var pageIndex = event.pageIndex ? event.pageIndex : 1;
  var pageSize = event.pageSize ? event.pageSize : 10;
  var orderBy = event.orderBy ? event.orderBy : 'rate';
  var state = 'desc';
  if (event.state == 'asc') {
    state = 'asc'
  }
  const countResult = await db.collection(dbName).where(_.or([
    {
      title: db.RegExp({
        regexp: filter,
        options: '1'
      })

    },
    {
      genre: db.RegExp({
        regexp: filter,
        options: '1'
      })
    },
    {
      actor: db.RegExp({
        regexp: filter,
        options: '1'
      })
    },
    {
      contries: db.RegExp({
        regexp: filter,
        options: '1'
      })
    }
  ])).count().catch(err => {
    return err
  })

  const total1 = countResult.total;
  const totalPage = Math.ceil(total1 / 10);
  var hasMore;
  if (pageIndex > totalPage || pageIndex == totalPage) {
    hasMore == false;
  } else {
    hasMore == true;
  }

  return await db
    .collection(dbName)
    .where(_.or([
      {
        title: db.RegExp({
          regexp: filter,
          options: 'i'
        })

      },
      {
        genre: db.RegExp({
          regexp: filter,
          options: 'i'
        })
      },
      {
        actor: db.RegExp({
          regexp: filter,
          options: 'i'
        })
      }
    ]))
    .orderBy(orderBy, state)
    .skip((pageIndex - 1) * pageSize)
    .limit(pageSize)
    .get()
    .then((res) => {
      res.data.map(v => {
        v.title = v.title.slice(0, v.title.indexOf(' '));
        v.engTitle = v.title.slice(v.title.indexOf(' ') + 1, -1);
      });
      res.hasMore = hasMore;
      return res;
    }).catch(err => {
      return err
    });
};
